package org.wanho.shop.service.impl;

import org.wanho.shop.dao.ItemDao;
import org.wanho.shop.dao.OrderDao;
import org.wanho.shop.dao.impl.ItemDaoImpl;
import org.wanho.shop.dao.impl.OrderDaoImpl;
import org.wanho.shop.entity.Item;
import org.wanho.shop.entity.Order;
import org.wanho.shop.entity.User;
import org.wanho.shop.service.OrderService;
import org.wanho.shop.util.StringUtil;
import org.wanho.shop.vo.Cart;

import java.util.List;

/**
 * Author：汤小洋
 * Date：2023-04-27 10:42
 * Description：<描述>
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();
    private ItemDao itemDao = new ItemDaoImpl();

    @Override
    public String create(Cart cart, User user) {
        Order order = new Order();
        String no = StringUtil.generateNo();
        order.setNo(no);
        order.setPrice(cart.getPrice());
        order.setUser(user);
        // 保存订单并返回对应的主键
        int orderId = orderDao.insert(order);
        order.setId(orderId);

        List<Item> items = cart.getItems();
        for (Item item : items){
            item.setOrder(order);
            itemDao.insert(item);
        }
        return no;
    }

    @Override
    public List<Order> findMyOrders(User user) {
        return orderDao.selectByUserId(user.getId());
    }

    @Override
    public Order findDetail(int id) {
        Order order = orderDao.selectDetailById(id);
        List<Item> items = itemDao.selectById(id);
        order.setItems(items);
        return order;
    }
}
